package com.lijinjiang.model;

import com.lijinjiang.exception.QueryException;
import com.lijinjiang.model.tree.Database;
import com.lijinjiang.model.tree.ServerConnection;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @ClassName QueryData
 * @Description 查询数据对象
 * @Author Li
 * @Date 2022/8/21 23:22
 * @ModifyDate 2022/8/21 23:22
 * @Version 1.0
 */
public class QueryData implements QueryObject {
    // 对应的数据库对象
    private Database database;

    private Connection connection; // 数据库连接

    private Statement statement; // statement接口

    private ResultSet resultSet; // 结果集

    // 此次查询的 SQL 语句
    private String sql;

    public QueryData(Database database, String sql) {
        this.sql = sql;
        this.database = database;
    }

    // 获取数据
    @Override
    public ResultSet getData() throws QueryException{
        try {
            setStatement();
            resultSet = this.statement.executeQuery(this.sql);
            return resultSet;
        } catch (SQLException se){
            throw new QueryException(se.getErrorCode() + " - " + se.getMessage());
        }
    }

    // 执行 sql
    public void execute() {
        try {
            setStatement();
            this.statement.execute(this.sql);
        } catch (SQLException se) {
            throw new QueryException(se.getErrorCode() + " - " + se.getMessage());
        }
    }

    // 获取执行 SQL 对象
    private void setStatement() throws SQLException {
        this.connection = this.database.getConnection();
        if (connection == null) {
            ServerConnection sc = this.database.getSc();
            Connection conn = sc.createConnection(database.getDbName());
            this.statement = conn.createStatement();
        } else {
            this.statement = this.database.getStatement();
        }
    }
}
